﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      CIS Customer ManagementHelper 
// Created By:     Tingrong Shi (trshi@wicresoft.com)
// Created Date:   2011-1-29
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using ASBCC.Database.EntityFramework;

namespace ASBCC.Business.CIS
{
    public static class CustomerManageHelper
    {
        /// <summary>
        /// 将一个Customer的状态设为未激活
        /// </summary>
        /// <param name="customerId"></param>
        public static void SetCustomerDisabled(int customerId)
        {
            using (var dc = new CCEntities())
            {
                dc.Customers.First(p => p.CustomerID == customerId).Disabled = true;
                dc.SaveChanges();
            }
        }

        /// <summary>
        /// 根据当前ID获取Name
        /// </summary>
        public static IEnumerable getName(int entityID)
        {
            using (var dc = new CCEntities())
            {
                var name = dc.Customers.FirstOrDefault(p => p.CustomerID == entityID).Name;
                return name;
            }
        }

        /// <summary>
        /// 根据当前用户权限获取可见客户
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public static string GetCustomerIDbyRoleID(string roleID)
        {
            using (var dc = new CCEntities())
            {
                var source = dc.sp_GetCustomerIDbyRoleID(roleID).ToList<Customer>();
                if (source == null || source.Count == 0)
                    return "0";
                string values = "";
                foreach (var customer in source)
                {
                    values += customer.CustomerID.ToString();
                    values += ",";
                }
                return values.Substring(0, values.Length - 1);
            }
        }

        /// <summary>
        /// CIO根据当前用户权限获取可见客户
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public static string GetCustomerIDbyRoleIDCIO(string roleID)
        {
            using (var dc = new CCEntities())
            {
                var source = dc.sp_GetCustomerIDbyRoleIDCIO(roleID).ToList<Customer>();
                if (source == null || source.Count == 0)
                    return "0";
                string values = "";
                foreach (var customer in source)
                {
                    values += customer.CustomerID.ToString();
                    values += ",";
                }
                return values.Substring(0, values.Length - 1);
            }
        }

        /// <summary>
        /// 根据RoleID查询当前用户可见Company
        /// </summary>
        public static string GetCompanyByRoleID(string RoleID)
        {
            using (var dc = new CCEntities())
            {
                var source = dc.sp_GetCompanybyRoleID(RoleID).ToList<Company>();
                if (source == null || source.Count == 0)
                    return "0";
                string values = "";
                foreach (var company in source)
                {
                    values += company.CompanyID.ToString();
                    values += ",";
                }
                return values.Substring(0, values.Length - 1);
            }
        }

        /// <summary>
        /// CIO根据RoleID查询当前用户可见Company
        /// </summary>
        public static string GetCompanyByRoleIDCIO(string RoleID)
        {
            using (var dc = new CCEntities())
            {
                var source = dc.sp_GetCompanyIDbyRoleIDCIO(RoleID).ToList<Company>();
                if (source == null || source.Count == 0)
                    return "0";
                string values = "";
                foreach (var company in source)
                {
                    values += company.CompanyID.ToString();
                    values += ",";
                }
                return values.Substring(0, values.Length - 1);
            }
        }

        public static string GetEmployeeNoByName(string name)
        {
            using (var dc = new CCEntities())
            {
                return dc.Employees.First(p => p.NameEN == name).EmployeeNo;
            }
        }

        /// <summary>
        /// 插入Customer
        /// </summary>
        public static void OnCustomerInserting(Customer customer, TrainingSource trainings, EducationSource educations, FamilySource familyInfos, WorkExprienceSource workExperience, PreferenceSource perference, ObjectContext dcs)
        {
            if (trainings != null)
            {
                if (!String.IsNullOrEmpty(trainings.Type))
                {
                    string[] type = trainings.Type.Split(',');
                    string[] time = trainings.Time.Split(',');
                    string[] endtime = trainings.EndTime.Split(',');
                    for (int i = 0; i < type.Count(); i++)
                    {
                        if (!String.IsNullOrEmpty(type[i]))
                        {
                            customer.CustomerTrainings.Add(new CustomerTraining()
                            {
                                Name = type[i],
                                Date = Convert.ToDateTime(time[i]),
                                EndDate = Convert.ToDateTime(endtime[i]),

                            });
                        }
                    }
                }
            }
            if (educations != null)
            {
                if (!String.IsNullOrEmpty(educations.School))
                {
                    string[] school = educations.School.Split(',');
                    string[] degree = educations.Degree.Split(',');
                    string[] startTime = educations.StartTime.Split(',');
                    string[] endTime = educations.EndTime.Split(',');
                    //string[] description1 = educations.Description.Split(',');
                    for (int i = 0; i < school.Count(); i++)
                    {
                        if (!String.IsNullOrEmpty(school[i]))
                        {
                            customer.Education.Add(new Education()
                            {
                                School = school[i],
                                Degree = degree[i],
                                StartTime = !String.IsNullOrEmpty(startTime[i]) ? Convert.ToDateTime(startTime[i]) : Convert.ToDateTime("2000/1/1"),
                                EndTime = !String.IsNullOrEmpty(endTime[i]) ? Convert.ToDateTime(endTime[i]) : Convert.ToDateTime("2000/1/1"),
                                //Description = description1[i]
                            });
                        }
                    }
                }
            }

            if (familyInfos != null)
            {
                if (!String.IsNullOrEmpty(familyInfos.Name))
                {
                    string[] name = familyInfos.Name.Split(',');
                    string[] relationship = familyInfos.Relationship.Split(',');
                    string[] workplace = familyInfos.WorkPlace.Split(',');
                    //string[] description2 = familyInfos.Description.Split(',');
                    for (int i = 0; i < name.Count(); i++)
                    {
                        if (!String.IsNullOrEmpty(name[i]))
                        {
                            customer.FamilyInfo.Add(new FamilyInfo()
                            {
                                Name = name[i],
                                Relationship = relationship[i],
                                WorkPlace = workplace[i],
                                //Description = description2[i]
                            });
                        }
                    }
                }
            }

            if (workExperience != null)
            {
                if (!String.IsNullOrEmpty(workExperience.CompanyName))
                {
                    string[] companyName = workExperience.CompanyName.Split(',');
                    string[] title = workExperience.Title.Split(',');
                    string[] startTime = workExperience.StartTime.Split(',');
                    string[] endTime = workExperience.EndTime.Split(',');
                    //string[] description3 = workExperience.Description.Split(',');
                    for (int i = 0; i < companyName.Count(); i++)
                    {
                        if (!String.IsNullOrEmpty(companyName[i]))
                        {
                            customer.WorkExperience.Add(new WorkExperience()
                            {
                                CompanyName = companyName[i],
                                Title = title[i],
                                StartTime = !String.IsNullOrEmpty(startTime[i]) ? Convert.ToDateTime(startTime[i]) : Convert.ToDateTime("2000/1/1"),
                                EndTime = !String.IsNullOrEmpty(endTime[i]) ? Convert.ToDateTime(endTime[i]) : Convert.ToDateTime("2000/1/1"),
                                //Description = description3[i]
                            });
                        }
                    }
                }
            }

            if (perference != null)
            {
                if (!String.IsNullOrEmpty(perference.List))
                {
                    string[] list = perference.List.Split(',');
                    string[] value = perference.Value.Split(',');
                    string[] level = perference.Level.Split(',');
                    for (int i = 0; i < list.Count(); i++)
                    {
                        if (!String.IsNullOrEmpty(list[i]))
                        {

                            int listid = Convert.ToInt32(list[i]);
                            int valueid = Convert.ToInt32(value[i]);
                            int levelid = Convert.ToInt32(level[i]);
                            var ss1 = dcs.CreateQuery<PreferencesList>("PreferencesLists");
                            var ss2 = dcs.CreateQuery<PreferencesValue>("PreferencesValues");
                            var ss3 = dcs.CreateQuery<PreferencesLevel>("PreferencesLevels");
                            customer.CustomerPreference.Add(new CustomerPreference()
                            {
                                //ListID=listid,
                                PreferencesList = ss1.First(p => p.ListID == listid),
                                //ValueID=valueid,
                                PreferencesValue = ss2.First(p => p.ValueID == valueid),
                                //LevelID=levelid,
                                PreferencesLevel = ss3.First(p => p.LevelID == levelid)
                            });

                        }
                    }
                }
            }
        }

        public static void OnCustomerUpdating(Customer customer, TrainingSource trainings, EducationSource educations, FamilySource familyInfos, WorkExprienceSource workExperience, PreferenceSource perference, ObjectContext dcs)
        {
            using (var dc = new CCEntities())
            {
                customer.CustomerTrainings.Load();
                foreach (var tra in customer.CustomerTrainings)
                {
                    dc.DeleteObject(dc.CustomerTrainings.First(p => p.TrainingID == tra.TrainingID));
                }
                customer.Education.Load();
                foreach (var edu in customer.Education)
                {
                    dc.DeleteObject(dc.Educations.First(p => p.EducationID == edu.EducationID));
                }
                customer.FamilyInfo.Load();
                foreach (var fam in customer.FamilyInfo)
                {
                    dc.DeleteObject(dc.FamilyInfos.First(p => p.FamilyInfoID == fam.FamilyInfoID));
                }
                customer.WorkExperience.Load();
                foreach (var wor in customer.WorkExperience)
                {
                    dc.DeleteObject(dc.WorkExperiences.First(p => p.WorkExperienceID == wor.WorkExperienceID));
                }
                var customerpre = dc.CustomerPreferences.Where(p => p.CustomerID == customer.CustomerID);
                foreach (var pre in customerpre)
                {
                    dc.DeleteObject(pre);
                }
                dc.SaveChanges();
                OnCustomerInserting(customer, trainings, educations, familyInfos, workExperience, perference, dcs);
            }
        }

        public static int InsertNewDepartment(string name)
        {
            using (var dc = new CCEntities())
            {
                var dep = dc.CustomerDepartments.FirstOrDefault(p => p.Name == name && p.Disabled == false);
                if (dep == null)
                {
                    CustomerDepartment department = new CustomerDepartment();
                    department.Name = name;
                    department.Description = name;
                    department.Disabled = false;
                    dc.AddObject("CustomerDepartments", department);
                    dc.SaveChanges();
                    return department.DepartmentID;
                }
                return dep.DepartmentID;
            }
        }

        public static string GetPreferencesList()
        {
            using (var dc = new CCEntities())
            {
                string lists = "<option value=\\\"\\\">--请选择--</option>";
                foreach (var list in dc.PreferencesLists)
                {
                    lists += ("<option value=" + list.ListID.ToString() + ">" + list.Name + "</option>");
                }
                return "\"" + lists + "\"";
            }
        }

        public static string GetPreferencesLevel()
        {
            using (var dc = new CCEntities())
            {
                string showlist = "";
                foreach (var list in dc.PreferencesLists)
                {
                    list.PreferencesLevels.Load();
                    var Levels = list.PreferencesLevels;
                    foreach (var Level in Levels)
                    {
                        showlist += ("{'When':'" + list.ListID + "','Value':'" + Level.LevelID + "','Text':'" + Level.Name + "'},");
                    }
                }
                if (showlist.Length > 0)
                {
                    showlist = "[" + showlist + "]";
                }
                return showlist;
            }
        }

        public static string GetPreferencesValue()
        {
            using (var dc = new CCEntities())
            {
                string showlist = "";
                foreach (var list in dc.PreferencesLists)
                {
                    list.PreferencesValues.Load();
                    var values = list.PreferencesValues;
                    foreach (var value in values)
                    {
                        showlist += ("{'When':'" + list.ListID + "','Value':'" + value.ValueID + "','Text':'" + value.Name + "'},");
                    }
                }
                if (showlist.Length > 0)
                {
                    showlist = "[" + showlist + "]";
                }
                return showlist;
            }
        }

        //public static void InsertPreference(int customerID, PreferenceSource preference)
        //{
        //    if (preference != null)
        //    {
        //        if (!String.IsNullOrEmpty(preference.List))
        //        {
        //            using (var dc = new CCEntities())
        //            {
        //                string[] list = preference.List.Split(',');
        //                string[] value = preference.Value.Split(',');
        //                string[] level = preference.Level.Split(',');
        //                for (int i = 0; i < list.Count(); i++)
        //                {
        //                    if (!String.IsNullOrEmpty(list[i]))
        //                    {

        //                        int listid = Convert.ToInt32(list[i]);
        //                        int valueid = Convert.ToInt32(value[i]);
        //                        int levelid = Convert.ToInt32(level[i]);
        //                        var cuspre = new CustomerPreference();
        //                        cuspre.Customer = dc.Customers.First(p => p.CustomerID == customerID);
        //                        cuspre.PreferencesList = dc.PreferencesLists.First(p => p.ListID == listid);
        //                        cuspre.PreferencesValue = dc.PreferencesValues.First(p => p.ValueID == valueid);
        //                        cuspre.PreferencesLevel = dc.PreferencesLevels.First(p => p.LevelID == levelid);
        //                        dc.AddObject("CustomerPreferences", cuspre);
        //                    }
        //                }
        //                dc.SaveChanges();
        //            }
        //        }
        //    }
        //}

        /// <summary>
        /// 获取Level的source
        /// </summary>
        /// <returns></returns>
        public static string[] GetCustomerLevels()
        {
            return Enum.GetNames(typeof(CustomerLevelHelper));
        }

        /// <summary>
        /// 获取Company的source
        /// </summary>
        /// <returns></returns>
        public static List<Company> GetCompanies()
        {
            using (var dc = new CCEntities())
            {
                var t = dc.PreferencesLevels.First();
                int de = t.PreferencesLists.First().ListID;
                return dc.Companies.Where(p => p.Disabled == false).ToList<Company>();
            }
        }

        /// <summary>
        /// 获取Department的source
        /// </summary>
        /// <returns></returns>
        public static List<CustomerDepartment> GetDepartments()
        {
            using (var dc = new CCEntities())
            {
                return dc.CustomerDepartments.Where(p => p.Disabled == false).ToList<CustomerDepartment>();
            }
        }

        /// <summary>
        /// 获取Definition的source
        /// </summary>
        /// <returns></returns>
        public static List<Definition> GetDefinitions()
        {
            using (var dc = new CCEntities())
            {
                return dc.Definitions.Where(p => p.Disabled == false).ToList<Definition>();
            }
        }

        /// <summary>
        /// 由customerId获取Customer信息
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public static Customer GetCustomerById(int customerId)
        {
            using (var dc = new CCEntities())
            {
                return dc.Customers.First(p => p.CustomerID == customerId);
            }
        }



        /// <summary>
        /// 获取某个Customer所对应的Eduction
        /// </summary>
        /// <param name="customerID"></param>
        /// <returns></returns>
        public static List<Education> GetEductionByCustomerID(string customerID)
        {
            using (var dc = new CCEntities())
            {
                int cID = Convert.ToInt32(customerID);
                return dc.Educations.Where(p => p.Customer.CustomerID == cID).ToList<Education>();
            }
        }

        /// <summary>
        /// 获取某个Customer所对应的FaminlyInfo
        /// </summary>
        /// <param name="customerID"></param>
        /// <returns></returns>
        public static List<FamilyInfo> GetFamilyInfoByCustmerID(string customerID)
        {
            using (var dc = new CCEntities())
            {
                int cID = Convert.ToInt32(customerID);
                return dc.FamilyInfos.Where(p => p.Customer.CustomerID == cID).ToList<FamilyInfo>();
            }
        }

        /// <summary>
        /// 获取某个Customer所对应的WorkExperience
        /// </summary>
        /// <param name="customerID"></param>
        /// <returns></returns>
        public static List<WorkExperience> GetWorkExperienceByCustmerID(string customerID)
        {
            using (var dc = new CCEntities())
            {
                int cID = Convert.ToInt32(customerID);
                return dc.WorkExperiences.Where(p => p.Customer.CustomerID == cID).ToList<WorkExperience>();
            }
        }

        /// <summary>
        /// 通过CompanyID判断Cluster
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public static string GetClusterByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.PCATs.Load();
                var pcat = company.PCATs.First();
                if (pcat != null)
                {
                    var procat = dc.Provinces.First(p => p.ProvinceID == pcat.ProvinceID).Name + ";" + dc.Categories.First(p => p.CateID == pcat.CateID).Name;
                    var province = dc.Provinces.First(p => p.ProvinceID == pcat.ProvinceID);
                    province.Clusters.Load();
                    var cluster = province.Clusters.FirstOrDefault();
                    return (cluster == null ? "" : cluster.Name) + ";" + procat;
                }
                return "";
            }
        }

        /// <summary>
        /// 通过CompanyID判断Cluster
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public static string GetAreaByCompanyID(int companyID)
        {
            using (var dc = new CCEntities())
            {
                var company = dc.Companies.First(p => p.CompanyID == companyID);
                company.Countries.Load();
                var country = company.Countries.FirstOrDefault();
                if (country != null)
                {
                    country.Areas.Load();
                    var area = country.Areas.FirstOrDefault(p => p.Disabled == false);
                    return (area == null ? "" : area.Name + "(" + area.Description + ")") + ";" + country.Name + "(" + country.Description + ")";
                }
                return "";
            }
        }

        /// <summary>
        /// 获取用户可见Province
        /// </summary>
        /// <param name="cil"></param>
        /// <returns></returns>
        public static List<Province> GetProvinceByUser(string cil)
        {
            using (var dc = new CCEntities())
            {
                List<Province> provinces = new List<Province>();
                var employee = dc.Employees.First(p => p.NameEN == cil);
                employee.Roles.Load();
                bool isCIDAdmin = false;
                foreach (var role in employee.Roles)
                {
                    if (role.Disabled == false && role.BelongsTo == "CID" && role.IsAdmin == true)
                    {
                        isCIDAdmin = true;
                        break;
                    }
                }
                if (isCIDAdmin)
                    provinces = dc.Provinces.Where(p => p.Disabled == false).ToList<Province>();
                else
                {
                    //获取该用户所有PCAT
                    List<PCAT> pcats1 = new List<PCAT>();
                    foreach (var role in employee.Roles)
                    {
                        role.PCATs.Load();
                        var pcat1 = role.PCATs.FirstOrDefault();
                        if (pcat1 != null && pcats1.FirstOrDefault(p => p.ProvinceID == pcat1.ProvinceID && p.CateID == pcat1.CateID) == null)
                            pcats1.Add(pcat1);

                    }

                    foreach (var pcat in pcats1)
                    {
                        var province = dc.Provinces.FirstOrDefault(p => p.ProvinceID == pcat.ProvinceID && p.Disabled == false);
                        if (province != null && (province.Name == "总部" || pcats1.Where(p => p.ProvinceID == pcat.ProvinceID).Count() == dc.PCATs.Where(p => p.ProvinceID == pcat.ProvinceID).Count()))
                            provinces.Add(province);
                    }
                }

                return provinces.OrderBy(p => p.ProvinceID).Distinct().ToList<Province>();
            }
        }

        /// <summary>
        /// 获取用户可见Category
        /// </summary>
        /// <param name="cil"></param>
        /// <returns></returns>
        public static List<Category> GetCategoryByUser(string cil)
        {
            using (var dc = new CCEntities())
            {
                List<Category> category = new List<Category>();
                var employee = dc.Employees.First(p => p.NameEN == cil);
                employee.Roles.Load();
                bool isCIDAdmin = false;
                foreach (var role in employee.Roles)
                {
                    if (role.Disabled == false && role.BelongsTo == "CID" && role.IsAdmin == true)
                    {
                        isCIDAdmin = true;
                        break;
                    }
                }
                if (isCIDAdmin)
                    category = dc.Categories.Where(p => p.Disabled == false).ToList<Category>();
                else
                {
                    int flag = 0;
                    List<PCAT> pcats1 = new List<PCAT>();
                    foreach (var role in employee.Roles)
                    {
                        role.PCATs.Load();
                        var pcat1 = role.PCATs.FirstOrDefault();
                        if (pcat1 != null && pcats1.FirstOrDefault(p => p.ProvinceID == pcat1.ProvinceID && p.CateID == pcat1.CateID) == null)
                            pcats1.Add(pcat1);

                    }
                    foreach (var pcat in pcats1)
                    {
                        var province = dc.Provinces.FirstOrDefault(p => p.ProvinceID == pcat.ProvinceID && p.Disabled == false);
                        var category2 = dc.Categories.FirstOrDefault(p => p.CateID == pcat.CateID && p.Disabled == false);
                        if (province != null && province.Name == "总部" && category2 != null)
                        {
                            category.Add(category2);
                        }
                        else
                            flag++;
                    }
                    if (flag > 0)
                    {
                        var category1 = dc.Categories.FirstOrDefault(p => p.Name == "Others" && p.Disabled == false);
                        if (category1 != null)
                            category.Add(category1);
                    }

                }

                return category.OrderBy(p => p.CateID).Distinct().ToList<Category>();
            }
        }

        /// <summary>
        /// 获取用户可见Country
        /// </summary>
        /// <param name="cil"></param>
        /// <returns></returns>
        public static string GetCountryByUser(string roles)
        {
            using (var dc = new CCEntities())
            {
                string[] role1 = roles.Split(',');
                List<Country> country = new List<Country>();
                bool isCIDAdmin = false;
                foreach (var role2 in role1)
                {
                    int role3 = int.Parse(role2);
                    var role = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.RoleID == role3);
                    if (role == null)
                        continue;
                    if (role.BelongsTo == "CIO" && role.IsAdmin == true)
                    {
                        isCIDAdmin = true;
                        break;
                    }
                    role.Countries.Load();
                    foreach (var coun in role.Countries)
                    {
                        if (coun.Disabled == false)
                            country.Add(coun);
                    }
                }
                if (isCIDAdmin)
                    country = dc.Countries.Where(p => p.Disabled == false).ToList<Country>();
                var country1 = country.Distinct().ToList<Country>();
                string returnvalue = "\"--请选择--\":\"0\",";
                foreach (var coun in country1)
                {
                    returnvalue += "\"" + coun.Name + "(" + coun.Description + ")" + "\":\"" + coun.CountryID.ToString() + "\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        /// 获取Department
        /// </summary>
        /// <returns></returns>
        public static string GetDepartmentSelectString()
        {
            using (var dc = new CCEntities())
            {
                var deapartments = dc.CustomerDepartments.Where(p => p.Disabled == false).ToArray().Distinct().OrderBy(p=>p.Name);
                string returnvalue = "\"--请选择--\":\"0\",";
                foreach (var deapartment in deapartments)
                {
                    returnvalue += "\"" + deapartment.Name + "\":\"" + deapartment.DepartmentID.ToString() + "\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        /// 获取Company
        /// </summary>
        /// <returns></returns>
        public static string GetCompanySelectString(string roles)
        {
            using (var dc = new CCEntities())
            {
                var companies = dc.sp_GetCompanybyRoleID(roles);
                string returnvalue = "\"--请选择--\":\"0\",";
                foreach (var company in companies)
                {
                    returnvalue += "\"" + company.Name.Replace("'", "").Replace("\"", "") + "\":\"" + company.CompanyID.ToString() + "\",";
                }
                return returnvalue.Substring(0, returnvalue.Length - 1);
            }
        }

        /// <summary>
        /// 检查客户姓名是否重复
        /// </summary>
        /// <returns></returns>
        public static bool CheckCustomerName(string name, string roles)
        {
            using (var dc = new CCEntities())
            {
                var customer = dc.Customers.FirstOrDefault(p => p.Name == name && p.Disabled == false && p.IsDraft != true && (p.CheckFlag == null || p.CheckFlag == 0));
                if (customer == null)
                    return true;
                else
                {
                    var companies = dc.sp_GetCompanybyRoleID(roles);
                    foreach (var company in companies)
                    {
                        if (dc.Customers.Where(p => p.Name == name && p.Company.CompanyID == company.CompanyID && p.Disabled == false && p.IsDraft != true && (p.CheckFlag == null || p.CheckFlag == 0)).Count() > 0)
                            return false;
                    }
                    return true;
                }
            }
        }

        /// <summary>
        /// customer页面直接创建公司
        /// </summary>
        public static string CreateCompany(string name, string provinceID, string categoryID, string address, string tel, string fax, string web, string zip, string description, string createBy)
        {
            using (var dc = new CCEntities())
            {
                int pid = int.Parse(provinceID);
                int cid = int.Parse(categoryID);
                Company c = new Company();
                c.Name = name;
                c.Address = address;
                c.Tel = tel;
                c.Fax = fax;
                c.Website = web;
                c.Zip = zip;
                c.Description = description;
                c.CreateBy = dc.Employees.First(p => p.NameEN == createBy);
                c.LastModifyBy = c.CreateBy;
                c.CreateTime = DateTime.Now;
                c.LastModifyTime = DateTime.Now;
                c.PCATs.Add(dc.PCATs.First(p => p.ProvinceID == pid && p.CateID == cid));
                dc.SaveChanges();
                var province = dc.Provinces.First(p => p.ProvinceID == pid);
                province.Clusters.Load();
                if (province.Clusters.Count > 0)
                    return c.CompanyID + ";" + province.Clusters.First().Name.ToString();
                else
                    return c.CompanyID + ";";
            }
        }

        /// <summary>
        /// 海外customer页面直接创建公司
        /// </summary>
        public static string CreateCompanyOver(string name, string countryID, string address, string tel, string fax, string web, string zip, string description, string createBy)
        {
            using (var dc = new CCEntities())
            {
                int cid = int.Parse(countryID);
                Company c = new Company();
                c.Name = name;
                c.Address = address;
                c.Tel = tel;
                c.Fax = fax;
                c.Website = web;
                c.Zip = zip;
                c.Description = description;
                c.CreateBy = dc.Employees.First(p => p.NameEN == createBy);
                c.LastModifyBy = c.CreateBy;
                c.CreateTime = DateTime.Now;
                c.LastModifyTime = DateTime.Now;
                c.Countries.Add(dc.Countries.First(p => p.CountryID == cid));
                dc.SaveChanges();
                var counrty = dc.Countries.First(p => p.CountryID == cid);
                counrty.Areas.Load();
                var area = counrty.Areas.FirstOrDefault();
                if (area != null)
                    return c.CompanyID + ";" + area.Name + "(" + area.Description + ")";
                else
                    return c.CompanyID + ";";
            }
        }

        /// <summary>
        /// 获取Customer的Training
        /// </summary>
        /// <param name="customerID"></param>
        /// <returns></returns>
        public static IEnumerable GetTrainingByCustomerID(int customerID)
        {
            using (var dc = new CCEntities())
            {
                var customer = dc.Customers.FirstOrDefault(p => p.CustomerID == customerID && p.Disabled == false);
                if (customer != null)
                {
                    customer.CustomerTrainings.Load();
                    return customer.CustomerTrainings;
                }
                return null;
            }
        }

        /// <summary>
        /// 判断是否为Customer 信息审核人员
        /// </summary>
        /// <param name="roles"></param>
        /// <returns></returns>
        public static bool CheckIsReviewer(string roles)
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.Name == "CID Reviewer");
                if (role == null)
                    return false;
                if (roles.Contains(role.RoleID.ToString()))
                    return true;
                return false;
            }
        }

        public static bool IfReviewerExist()
        {
            using (var dc = new CCEntities())
            {
                var role = dc.Roles.FirstOrDefault(p => p.Disabled == false && p.Name == "CID Reviewer");
                if (role != null)
                {
                    role.Employees.Load();
                    if (role.Employees.Count > 0)
                        return true;
                }
                return false;
            }
        }

    }

    public enum CustomerLevelHelper
    {
        level1 = 0,
        level2 = 1,
        level3 = 2,
        level4 = 3,
        level5 = 4
    }

    public class TrainingSource
    {
        public string Type { get; set; }
        public string Time { get; set; }
        public string EndTime { get; set; }
        public string Comment { get; set; }
    }

    public class EducationSource
    {
        public string Degree { get; set; }
        public string School { get; set; }
        public string Description { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
    }

    public class FamilySource
    {
        public string Name { get; set; }
        public string Relationship { get; set; }
        public string WorkPlace { get; set; }
        public string Description { get; set; }
    }

    public class WorkExprienceSource
    {
        public string CompanyName { get; set; }
        public string Title { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
        public string Description { get; set; }
    }

    public class PreferenceSource
    {
        public string List { get; set; }
        public string Value { get; set; }
        public string Level { get; set; }
    }

    public class PerferenceSelectModel
    {
        public string When { get; set; }
        public string Value { get; set; }
        public string Text { get; set; }
    }
}
